<?php

namespace app\admin\controller;

use think\Db;

class Order
{
    public function __construct()
    {
        Admin_auth();
    }

    public function index()
    {
        $cancel = request()->request('cancel');
        $order_id = input('get.order_id');
        if($cancel){
            $page = input('get.page');
            if(Db::table('order')->where(['order_id'=>$order_id,'status'=>['between','2,4']])->update(['status'=>7])){
                $order = Db::table('order')->where(['order_id'=>$order_id])->find();
                if ($order['status'] > 1) {
                    //退款功能
                    if ($order['payment'] == 'wxpay') {
                        $pay_bool = false;
                        //微信
                        vendor('wxpayv_app.WxPay#Api');
                        $input = new \WxPayRefund();
                        $mchid = \WxPayConfig::$mchid;
                        $input->SetOut_trade_no($order['order_id']);         //自己的订单号
                        $input->SetTransaction_id(null);     //微信官方生成的订单流水号，在支付成功中有返回
                        $input->SetOut_refund_no($order['order_id'] . '_exit');         //退款单号
                        $input->SetTotal_fee($order['last_price'] * 100);         //订单标价金额，单位为分
                        $input->SetRefund_fee($order['last_price'] * 100);            //退款总金额，订单总金额，单位为分，只能为整数
                        $input->SetOp_user_id($mchid);
                        $info = \WxPayApi::refund($input);
                        if ($info['return_code'] == 'SUCCESS') {
                            //退款申请成功
                            $pay_bool = true;
                        }
                    }else{
                        $pay_bool = false;
                        //alipay退款
                        $this->alipay_config = Db::table("payment")->find();
                        vendor('alipay.AopSdk');
                        $aop = new \AopClient ();
                        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                        $aop->appId = $this->alipay_config['app_id'];
                        $aop->rsaPrivateKey = $this->alipay_config['privatekey'];
                        $aop->alipayrsaPublicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB';
                        $aop->apiVersion = '1.0';
                        $aop->signType = 'RSA';
                        $aop->postCharset = 'utf-8';
                        $aop->format = 'json';
                        vendor('alipay.aop.request.AlipayTradeRefundRequest');
                        $request = new \AlipayTradeRefundRequest();
                        $request->setBizContent("{" .
                            "    \"out_trade_no\":\"" . $order_id . "\"," .
                            "    \"trade_no\":\"\"," .
                            "    \"refund_amount\":\"" . $order['last_price'] . "\"," .
                            "    \"refund_reason\":\"途骑退款\"," .
                            "    \"out_request_no\":\"" . $order_id . "\"," .
                            "    \"operator_id\":\"\"," .
                            "    \"store_id\":\"\"," .
                            "    \"terminal_id\":\"\"" .
                            "}");
                        $result = $aop->execute($request);
                        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                        $resultCode = $result->$responseNode->code;
                        if (!empty($resultCode) && $resultCode == 10000) {
                            if ($result->$responseNode->msg == "Success" && $result->$responseNode->refund_fee == $order['last_price']) {
                                //退款申请成功
                                $pay_bool = true;
                            }
                        }
                    }
                    if($pay_bool){
                        //取消订单，退还优惠券
                        Db::table('order')->where(['order_id' => $order_id])->update(['status' => 6, 'cancel_time' => time()]);
                        if (!empty($order['red_id'])) {
                            Db::table('red_packet')->where(['uid' => $order['uid'], 'id' => $order['red_id']])->setDec('flag');
                        }
                    }
                } else {
                    //取消订单，退还优惠券
                    Db::table('order')->where(['order_id' => $order_id])->update(['status' => 7, 'cancel_time' => time()]);
                    if (!empty($order['red_id'])) {
                        Db::table('red_packet')->where(['uid' => $order['uid'], 'id' => $order['red_id']])->setDec('flag');
                    }
                }

                push(md5($order['uid']),json_encode(['type'=>0,'message'=>'您的订单已被系统取消','parameters'=>$order_id]),'user');
                insert_message('user',$order['uid'],'系统提示','您的订单已被系统取消','0',$order_id);

                if($order['advance_receive'] == 1){
                    push(md5($order['seller_id']),json_encode(['type'=>0,'message'=>'您的订单已被系统取消','parameters'=>$order_id]),'seller');
                    insert_message('seller',$order['seller_id'],'系统提示','您的订单已被系统取消','0',$order_id);
                }

                if(!empty($order['express_id'])){
                    push(md5($order['express_id']),json_encode(['type'=>0,'message'=>'您的订单已被系统取消','parameters'=>$order_id]),'express');
                    insert_message('express',$order['express_id'],'系统提示','您的订单已被系统取消','0',$order_id);
                }
            }
            redirect(url('order/index') . '?page=' . $page);
            exit;
        }else{
            $aid = input('get.aid');
            $status = input('get.status');
            $express_id = input('get.express_id');
            $seller_id = input('get.seller_id');
            $start_time = input('get.start_time');
            $end_time = input('get.end_time');
            $where = [];
            $where_exp = [];
            if (!empty($aid)) {
                $where['order.aid'] = $aid;
                $where_exp['aid'] = $aid;
            }
			$expresslist = Db::table('express')->whereIn('aid', session('aid'))->where($where_exp)->select();
			$sellerlist = Db::table('seller')->whereIn('aid', session('aid'))->where($where_exp)->select();
            if (!empty($order_id)) {
                $where['order.order_id'] = $order_id;
            }
			if (!empty($status)) {               
				if($status == 8){
					$where['order.status'] = 2;
					$where['order.advance_receive'] = 0;
				}else{
					$where['order.status'] = $status;
				}
            }
			if (!empty($express_id)) {
                $where['order.express_id'] = $express_id;
            }
			if (!empty($seller_id)) {
                $where['order.seller_id'] = $seller_id;
            }
			if (!empty($start_time) || !empty($end_time)) {
                $where['order.time'] = ['between',[strtotime($start_time),strtotime($end_time.' 23:59:59')]];
            }
			//var_dump($where);exit;
            $pages = pages('order', $where, input('get.page'));
			if(session('aid')){
				$data = Db::view('order')->view('seller',['phone'=>'sellerphone'],'seller.id=order.seller_id','LEFT')->view('express',['name'=>'express_name'],'express.id=order.express_id','LEFT')->whereIn('order.aid', session('aid'))->where($where)->limit($pages['limit'])->order('time desc')->select();
			}else{
				$data = Db::view('order')->view('seller',['phone'=>'sellerphone'],'seller.id=order.seller_id','LEFT')->view('express',['name'=>'express_name'],'express.id=order.express_id','LEFT')->where($where)->limit($pages['limit'])->order('time desc')->select();
			}
			$last_time = Db::table('order')->whereIn('aid', session('aid'))->where($where)->max('time');
            //$data = Db::table('order')->whereIn('aid', session('aid'))->where($where)->limit($pages['limit'])->order('time desc')->select();
            return view('', ['data' => $data, 'last_time' => $last_time, 'expresslist' => $expresslist, 'sellerlist' => $sellerlist, 'pages' => $pages['pages']]);
        }
    }

    public function del()
    {
        $id = input('get.id') ? input('get.id') : 0;
        $page = input('get.page');
        Db::table('order')->whereIn('aid', session('aid'))->delete($id);
        redirect(url('/admin/order') . '?page=' . $page);
        exit;
    }

    public function examine()
    {
        $pages = pages('user', ['status' => 2], input('get.page'));
        $data = Db::table('user')->where(['type' => 1, 'status' => 2])->limit($pages['limit'])->order('id desc')->select();
        return view('', ['data' => $data, 'pages' => $pages['pages']]);
    }

    public function detail()
    {
        $order_id = input('get.order_id') ? input('get.order_id') : 0;
        $data = Db::table('order_detail')->where('order_id', $order_id)->select();
        $info = Db::table('order')->where('order_id', $order_id)->find();
        $info['data'] = $data;
        return view('', ['info' => $info]);
    }

    public function setting()
    {
        $tab = input('get.tab');
        if (request()->isPost()) {
            $data = request()->post();
            $type = input('get.type');
            if ($type == 'ali') {
                Db::table('payment')->where(['id' => 1])->update($data);
            } else {
                $tab = 'wxpay';
                unset($data['appclient_key']);
                unset($data['apiclient_cert']);
                Db::table('wxpay')->where('id', 1)->update($data);
            }
            file_get_contents(APP_PATH . '../vendor/wxpayv_app/apiclient_cert.pem', request()->request('apiclient_cert'));
            file_get_contents(APP_PATH . '../vendor/wxpayv_app/apiclient_key.pem', request()->request('apiclient_key'));
        }
        $wxdata = Db::table('wxpay')->order('id desc')->find();
        $data = Db::table('payment')->find();
        $apiclient_cert = file_get_contents(APP_PATH . '../vendor/wxpayv_app/apiclient_cert.pem');
        $apiclient_key = file_get_contents(APP_PATH . '../vendor/wxpayv_app/apiclient_key.pem');
        return view('', ['data' => $data, 'wxdata' => $wxdata, 'tab' => $tab, 'apiclient_cert' => $apiclient_cert, 'apiclient_key' => $apiclient_key]);
    }

    //调度系统汇总
    public function dispatch()
    {
        $this_time = time();
        $aid = request()->get('aid');
        $order_id = request()->request('order_id');
        $order = Db::table('order')->where('order_id', $order_id)->find();
        if (request()->isPost()) {
            $msg['state'] = 0;
            /*if (!empty($order['express'])) {
                $msg['msg'] = '调度失败，已被配送员接单';
            } else {*/
                if ($order['status'] == 5) {
                    $msg['msg'] = '无法调度，订单已完成';
                } else {
                    $uid = request()->request('uid');
                    $express = Db::table('express')->where('id', $uid)->find();
                    if ($express['business'] == 1 && ($express['active_time'] + 300) > $this_time) {
                        $msg['state'] = 1;
                        $data['express_id'] = $uid;
                        $data['status'] = 3;
                        Db::table('order')->where('order_id', $order_id)->update($data);

                        //push 配送 被调度
                        push(md5($uid), json_encode(['type' => 6, 'message' => '您有一条私人订单，请及时处理', 'parameters' => $order_id]), 'express');
                        insert_message('express', $uid, '订单提醒', '您有一条私人订单，请及时处理', 6, $order_id);

                        //push 用户
                        push(md5($order['uid']), json_encode(['type' => 2, 'message' => '您的订单已被配送员接单', 'parameters' => $order_id]), 'user');
                        insert_message('user', $uid, '订单提醒', '您的订单已被配送员接单', 2, $order_id);

                        $msg['msg'] = '分配成功';
                    } else {
                        $msg['msg'] = '配送员暂时不在线，无法派单';
                    }
                }
//            }
            return json($msg);
        } else {
            $order_id = request()->get('order_id');
            if ($order_id != '') {
                $express_id = request()->get('express_id');
                $where['business'] = 1;
                if (!empty($express_id)) {
                    $where['id'] = ['<>', $express_id];
                }
                $center['lng'] = $order['lng'];
                $center['lat'] = $order['lat'];

                $express = Db::table('express')->where($where)->where('active_time>' . ($this_time - 300))->whereIn('aid', session('aid'))->select();
                $express_info = Db::table('express')->where(['id' => $express_id])->find();
                $seller_info = Db::table('seller')->field('lat,lng')->where(['id' => $order['seller_id']])->find();
                if (count($express_info) > 0) {
                    $express[count($express)] = $express_info;
                }
                $express_str = '';

                foreach ($express as $v) {
                    $count = Db::table('order')->where(['express_id' => $v['id'], 'status' => 3])->count();
                    if ($v['lng']) {
                        $express_str .= $v['lng'] . ',' . $v['lat'] . ',' . $v['name'] . ',' . $count . ',' . $v['id'] . '&';
                    }
                }
                $icon = '/express.png';
                $express_str = substr($express_str, 0, strlen($express_str) - 1);
				//var_dump($seller_info);exit;
                return view('', ['express_str' => $express_str, 'center' => $center,'seller_info' => $seller_info, 'order_id' => $order_id, 'icon' => $icon]);
            } else {
                $where = [];
                if (!empty($aid)) {
                    $where['aid'] = $aid;
                }
                $type = request()->get('type');
                if ($type == 'express') {
                    $pages = pages('express', $where, input('get.page'));
                    $data = Db::table('express')->whereIn('aid', session('aid'))->where($where)->limit($pages['limit'])->order('status desc,active_time desc')->select();
                    foreach ($data as $k => $v) {
                        if (($v['active_time']+300) >= time()  && $v['business'] == 1) {
                            $data[$k]['active'] = true;
                        } else {
                            $data[$k]['active'] = false;
                        }
                    }
                    return view('dispatch_express', ['data' => $data, 'pages' => $pages['pages']]);
                } elseif ($type == 'order') {
                    $where['order.status'] = ['between','2,4'];
                    $where['order.advance_receive'] = 1;
                    $pages = pages('order', $where, input('get.page'));
                    //$data = Db::table('order')->whereIn('aid', session('aid'))->where($where)->limit($pages['limit'])->order('time desc')->select();
					if(session('aid')){
						$data = Db::view('order')->view('seller',['phone'=>'sellerphone'],'seller.id=order.seller_id','LEFT')->view('express',['name'=>'express_name'],'express.id=order.express_id','LEFT')->whereIn('order.aid', session('aid'))->where($where)->limit($pages['limit'])->order('time desc')->select();
					}else{
						$data = Db::view('order')->view('seller',['phone'=>'sellerphone'],'seller.id=order.seller_id','LEFT')->view('express',['name'=>'express_name'],'express.id=order.express_id','LEFT')->where($where)->limit($pages['limit'])->order('time desc')->select();
					}
                    $last_time = Db::table('order')->whereIn('aid', session('aid'))->where($where)->max('time');
                    return view('dispatch_order', ['data' => $data,'last_time'=>$last_time ,'pages' => $pages['pages']]);
                } else {
                    return view('dispatch_system');
                }
            }
        }
    }

    public function socket()
    {
        $aid = (int)request()->get('aid');
        if (!empty($aid)) {
            $where['aid'] = $aid;
        }
        $type = request()->get('type');
        if ($type == 'order') {
            $where['status'] = ['between','2,4'];
            return Db::table('order')->whereIn('aid', session('aid'))->where($where)->max('time');
        } elseif ($type == 'dispatch_order') {
			$where['status'] = ['between','2,4'];
            $where['advance_receive'] = 1;
            return Db::table('order')->whereIn('aid', session('aid'))->where($where)->max('time');
        } elseif ($type == 'express') {
            $this_time = time();
            $where['business'] = 1;
            $pages = pages('express', $where, input('get.page'));
            $data = Db::table('express')->whereIn('aid', session('aid'))->where($where)->limit($pages['limit'])->order('status desc,active_time desc')->select();
            foreach ($data as $k => $v) {
                if (($v['active_time'] + 300) < $this_time && $v['business'] == 1) {
                    $data[$k]['active'] = false;
                } else {
                    $data[$k]['active'] = true;
                }
                $data[$k]['express_type_name'] = Db::table('express_type')->where('id', $v['express_type'])->value('name');
            }

        }
    }
}
